package com.woniu.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.org.apache.xpath.internal.operations.Or;
import com.woniu.entity.*;
import com.woniu.entity.vo.OrderVo;
import com.woniu.mapper.BookMapper;
import com.woniu.mapper.OrderMapper;
import com.woniu.product.DelayProduct;
import com.woniu.service.OrderService;
import com.woniu.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private DelayProduct delayProduct;
    /**
     * 用户下单接口
     * 实现步骤
     * 1:检查用户购买的商品中是否有库存不足的
     *      有：直接返回，不能下单。给出哪个商品不足的提示信息
     *      没有：走到第二步
     *
     * 2：往订单表写数据
     *
     * 3：往订单详情表写数据（批量插入）
     *
     * 4：修改购物车状态为已下单（批量处理）
     *
     * 5：修改商品的库存
     *
     * 6：发送一个延迟15分钟校验订单状态的延迟队列
     *
     * @param orderVo
     * @param jwt
     * @return
     */
    @Transactional
    @Override
    public ResData<?> addOrder(OrderVo orderVo, String jwt) {
        try {
            Map userInfo = JWTUtil.getJWTUserInfo(jwt);
            Long userId = (Long) userInfo.get("userId");
//            1:检查用户购买的商品中是否有库存不足的
//                         有：直接返回，不能下单。给出哪个商品不足的提示信息
//                         没有：走到第二步
            List<UserCart> userCarts = orderMapper.checkBuyBookCount(orderVo.getIds(), userId.intValue());

//            List<UserCart> bookCount = new ArrayList<>();
//            //判断库存
//            userCarts.forEach(e ->{
//                if(e.getBuyNum() > e.getStoreCount()){
//                    bookCount.add(e);
//                }
//            });
//            if(!CollectionUtils.isEmpty(bookCount)){
//                //有问题，后续处理
//                return new ResData<>().ok(bookCount);
//            }
            List<UserCart> bookBuyNumGtCount = userCarts.stream().filter(e -> e.getBuyNum() > e.getStoreCount())
                    .collect(Collectors.toList());

            if(!CollectionUtils.isEmpty(bookBuyNumGtCount)){
//                return new ResData<>().ok(bookBuyNumGtCount);     //原版做法
                //自定义错误码
                return new ResData<>().fail(bookBuyNumGtCount,ResEnum.NO_BOOK_COUNT);
            }

            //2：往订单表写数据
            Order order = new Order();
            order.setUserId((userId.intValue()));
            order.setAddressId(orderVo.getAddressId());

            BigDecimal orderTotalPrice = BigDecimal.ZERO;
            //计算订单总价格
            for (UserCart userCart : userCarts) {
                orderTotalPrice = orderTotalPrice.add(userCart.getTotalPrice());
            }
            order.setTotalPrice(orderTotalPrice);
            SnowflakeIdGenerator snowflakeIdGenerator = new SnowflakeIdGenerator();
            long orderNum = snowflakeIdGenerator.nextId();  //雪花ID
            order.setOrderNum(String.valueOf(orderNum));

            orderMapper.addOrder(order);

            //3：往订单详情表写数据（批量插入）
            List<OrderItem> orderItemList = new ArrayList<>();
            userCarts.forEach(e ->{
                OrderItem orderItem = new OrderItem();
                orderItem.setBuyCount(e.getBuyNum());
                orderItem.setBookId(e.getBookId());
                orderItem.setBookName(e.getName());
                orderItem.setOrderId(String.valueOf(orderNum));
                orderItem.setSumPrice(e.getTotalPrice());
                orderItem.setPrice(e.getBuyPrice());
                orderItemList.add(orderItem);
            });
            orderMapper.addOrderItem(orderItemList);

            //4：修改购物车的状态为已下单
            orderMapper.updateUserCartState(orderVo.getIds());

            //5：删除 redis 缓存内容
            updateBookCount(userCarts);
//            for (UserCart userCart : userCarts) {
//                redisTemplate.delete("bookDetail-"+userCart.getBookId());
//            }
            //6：发送一个延迟15分钟校验订单状态的延迟队列
            delayProduct.send(String.valueOf(orderNum),"checkOrder",5000);
            return new ResData<>().ok(order);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 查询用户订单信息
     * @param pageData
     * @return
     */
    @Override
    public ResData<?> queryOrder(PageData<Order> pageData,String jwt) {
        try {
            Map userInfo = JWTUtil.getJWTUserInfo(jwt);
            Long userId = (Long) userInfo.get("userId");
            pageData.getParam().setUserId(userId.intValue());
            PageHelper.startPage(pageData.getPageNum(), pageData.getPageSize());
            List<Order> orders = orderMapper.queryOrder(pageData.getParam());
            PageInfo pageInfo = new PageInfo(orders);

            return new ResData<>().ok(pageInfo);
        } catch (ParseException e) {
            return new ResData<>().fail(ResEnum.FAIL);
        }
    }

    /**
     * 用户点击购物车之后，进入确认订单页面。查询相关数据
     * 1、查询出所有订单详细信息
     * 2、查询出图书详细信息（图片）
     * 3、查询出订单收货地址详细信息
     * 4、统一返回
     *
     * @param order
     * @return
     */
    @Override
    public ResData<?> confirmOrder(Order order) {
        try {
            //1、查询出所有订单详细信息
            List<OrderItem> orderItemList = orderMapper.queryOrderItem(order.getOrderNum());
            //2、查询出图书详细信息（图片）
            orderItemList.forEach(orderItem -> {
                Book book = bookMapper.queryBookDetailByBookId(orderItem.getBookId());
                orderItem.setImgSrc(book.getImgSrc());
            });
            //3、查询出订单收货地址详细信息
            Address address = orderMapper.queryAddressById(order.getAddressId());
            Map map = new HashMap();
            map.put("orderList",orderItemList);
            map.put("address",address);

            return new ResData<>().ok(map);
        } catch (Exception e) {
            return new ResData<>().fail(ResEnum.FAIL);
        }
    }

    @Override
    public ResData<?> cancelOrder(String orderNum) {
        try {
            Integer i = orderMapper.cancelOrder(orderNum);
            return new ResData<>().ok();
        } catch (Exception e) {
            return new ResData<>().fail(ResEnum.FAIL);
        }

    }

    @Override
    public ResData<?> payOrder(String orderNum) {
        try {
            Integer i = orderMapper.payOrder(orderNum);
            return new ResData<>().ok();
        } catch (Exception e) {
            return new ResData<>().fail(ResEnum.FAIL);
        }
    }

    @Override
    public ResData<?> comment(String orderNum,Integer score, String comment) {
        try {
            Integer i = orderMapper.commentOrder(orderNum,score,comment);
            return new ResData<>().ok();
        } catch (Exception e) {
            return new ResData<>().fail(ResEnum.FAIL);
        }
    }

    //延迟双删
    public void updateBookCount(List<UserCart> userCarts) throws InterruptedException {
        List<String> redisBookKey = new ArrayList<>();
        for (UserCart userCart : userCarts) {
            redisBookKey.add("bookDetail-"+userCart.getBookId());
        }
        redisTemplate.delete(redisBookKey);

        //5：修改商品的库存
        orderMapper.updateBookCount(userCarts);

        Thread.sleep(200);

        redisTemplate.delete(redisBookKey);
    }
}
